package com.example.demo.HTcontroller;


import com.alibaba.fastjson.JSONObject;
import com.example.demo.Service.adminService;
import com.example.demo.entity.Return;
import com.example.demo.entity.admin;
import com.example.demo.mapperDao.AdminDao;
import com.google.gson.JsonObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/htApi")
public class adminColl extends adminService {
    @Autowired
    AdminDao adminDao;

    //登录
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public Return login(@RequestBody JSONObject jsonObject) {
        admin admin = new admin(0, jsonObject.getString("user"), jsonObject.getString("pwd"), 0);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getUser(), admin.getPwd());
        try {
            subject.login(token);
            return new Return(1, "ok");
        } catch (UnknownAccountException e) {
            return new Return(0, "用户名为空");
        } catch (IncorrectCredentialsException e) {
            return new Return(-1, "密码错误");
        }
    }

    //登录功能测试
    @RequestMapping("/testshiro")
    public Return testshiro() {
        return new Return(1, "testshiro");
    }

    //授权功能测试
    @RequestMapping("/testshiro2")
    public Return testshiro2() {
        return new Return(1, "testshiro2");
    }

    //退出
    @RequestMapping("/logout")
    public Return out() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Return(1, "out");
    }

    //提示去登录
    @RequestMapping("/toLogin")
    public Return toLogin() {
        return new Return(-1, "请先登录");
    }

    //提示去授权
    @RequestMapping("/toPower")
    public Return toPower() {
        return new Return(-1, "没有权限");
    }
}
